<template>
  <div class="register-container">
    <div class="container-narrow">
      <div class="text-center">
        <h1 class="title">创建账户</h1>
        <p class="text-mutedh">请填写注册信息</p>
      </div>

      <a-card class="register-card">
        <a-form
          :model="formState"
          name="register"
          @finish="onFinish"
          :rules="rules"
          layout="vertical"
        >
          <a-form-item label="用户名" name="nickName">
            <a-input v-model:value="formState.nickName" size="large" placeholder="请输入用户名">
              <template #prefix>
                <UserOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="邮箱" name="email">
            <a-input v-model:value="formState.email" size="large" placeholder="请输入邮箱地址">
              <template #prefix>
                <MailOutlined />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="密码" name="password">
            <a-input-password
              v-model:value="formState.password"
              size="large"
              placeholder="请输入密码"
            >
              <template #prefix>
                <LockOutlined />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item label="确认密码" name="confirmPassword">
            <a-input-password
              v-model:value="formState.confirmPassword"
              size="large"
              placeholder="请再次输入密码"
            >
              <template #prefix>
                <LockOutlined />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item label="验证码" name="checkCode">
            <div class="captcha-container">
              <a-input
                v-model:value="formState.checkCode"
                size="large"
                placeholder="请输入验证码"
                style="width: 60%"
              />
              <div class="captcha-image-container">
                <img
                  v-if="captchaData"
                  :src="captchaData"
                  alt="验证码"
                  class="captcha-image"
                  @click="refreshCaptcha"
                />
                <div v-else class="captcha-placeholder" @click="refreshCaptcha">
                  <ReloadOutlined />
                  <span>点击获取验证码</span>
                </div>
              </div>
            </div>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" html-type="submit" size="large" :loading="loading" block>
              注册
            </a-button>
          </a-form-item>
        </a-form>

        <div class="text-center mt-8">
          <span class="text-muted">已有账户？</span>
          <a @click="goToLogin">立即登录</a>
        </div>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined, LockOutlined, MailOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { registerUsingPost, checkCodeUsingGet } from '@/api/accountController'
import { handleApiError, showError, showSuccess } from '@/utils/error'

const router = useRouter()
const loading = ref(false)
const captchaData = ref('')
const checkCodeKey = ref('')

const formState = reactive({
  nickName: '',
  email: '',
  password: '',
  confirmPassword: '',
  checkCode: '',
  checkCodeKey: ''
})

const rules = {
  nickName: [{ required: true, message: '请输入用户名' }],
  email: [
    { required: true, message: '请输入邮箱地址' },
    { type: 'email', message: '请输入正确的邮箱格式' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, message: '密码长度至少6位' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: async (_: any, value: string) => {
        if (value && value !== formState.password) {
          throw new Error('两次输入的密码不一致')
        }
      }
    }
  ],
  checkCode: [{ required: true, message: '请输入验证码' }]
}

const onFinish = async (values: any): Promise<void> => {
  try {
    loading.value = true
    const { confirmPassword, ...registerData } = values
    const finalData = {
      ...registerData,
      checkCodeKey: checkCodeKey.value
    }
    const response = await registerUsingPost(finalData)

    if (response.data.code === 200) {
      showSuccess('注册成功')
      router.push('/login')
    } else {
      showError(response.data.info || '注册失败')
      refreshCaptcha()
    }
  } catch (error) {
    const errorInfo = handleApiError(error)
    showError(errorInfo)
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

const refreshCaptcha = async (): Promise<void> => {
  try {
    const response = await checkCodeUsingGet()

    if (response.data.code === 200 && response.data.data) {
      captchaData.value = response.data.data.checkCode
      checkCodeKey.value = response.data.data.checkCodeKey
      formState.checkCode = ''
    } else {
      showError(response.data.info || '获取验证码失败')
    }
  } catch (error) {
    const errorInfo = handleApiError(error)
    showError(errorInfo)
  }
}

const goToLogin = (): void => {
  router.push('/login')
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.register-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.container-narrow {
  width: 100%;
  max-width: 420px;
  margin: 0 auto;
}

.title {
  font-size: 26px;
  font-weight: 600;
  margin-bottom: 8px;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.register-card {
  margin-top: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  background: rgba(255, 255, 255, 0.98);
  border: none;
}
.text-mutedh {
  color: rgba(255, 255, 255, 0.9);
  font-size: 15px;
}

.text-muted {
  color: rgba(27, 26, 26, 0.9);
  font-size: 15px;
}

.mt-8 {
  margin-top: 8px;
}

.captcha-container {
  display: flex;
  gap: 12px;
  align-items: stretch;
}

.captcha-image-container {
  width: 40%;
  height: 40px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.captcha-image-container:hover {
  border-color: var(--color-primary);
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}

.captcha-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--color-muted-text);
  font-size: 12px;
  gap: 4px;
}

.captcha-placeholder:hover {
  background-color: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .container-narrow {
    max-width: 100%;
    padding: 0 16px;
  }

  .register-container {
    padding: 16px;
  }

  .title {
    font-size: 22px;
  }
}
</style>
